package user.self.defined;

import static io.netty.handler.codec.http.HttpHeaders.Names.CONTENT_TYPE;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.alibaba.fastjson.JSONObject;
import com.freedom.web.mymvc.common.SystemInterface;
import com.freedom.web.mymvc.utils.ByteBufUtils;
import com.freedom.web.mymvc.utils.LoggerUtils;
import com.freedom.web.mymvc.utils.ConstantsUtils;
import com.freedom.web.mymvc.utils.ViewType;
import com.freedom.web.mymvc.view.ModelAndView;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaders;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.util.CharsetUtil;

public class User implements SystemInterface {

	// logger
	private static final Logger logger = LogManager.getLogger(User.class);

	public ModelAndView service(FullHttpRequest request, FullHttpResponse response) throws Exception {
		LoggerUtils.debug(logger, "user invoked...by [" + request.getMethod() + " " + request.getUri() + " "
				+ request.getProtocolVersion());

		// 1)提取出request的内容
		String method = request.getMethod().toString();
		String uri = request.getUri();
		String httpVersion = request.getProtocolVersion().toString();
		HttpHeaders head = request.headers();
		String content = ByteBufUtils.getContent(request.content());
		//
		// 2)设置response
		{ // 比如设置cookie啥的
			// response.setStatus(null);
			// JSONObject object = new JSONObject();
			// object.put("error", 1);
			// object.put("status", HttpResponseStatus.OK.toString());
			// object.put("message", "Hello World");
			// response.headers().set(CONTENT_TYPE, MyConstants.JSON);
			//Set-Cookie: k1=v1;k2=v2
			
			
		}
		//
		// 3)构造Model,用于渲染后面的页面
		VelocityContext model = new VelocityContext();
		{
			model.put("azkaban_name", "Test");
			model.put("azkaban_label", "My Local Azkaban");
			model.put("azkaban_color", "#FF0000");
			model.put("context", "web");
		}
		// 4)指定要渲染的view路径
		String view = "azkaban/webapp/servlet/velocity/login.vm";
		//
		// 5)万事俱备，返回给框架
		//
		// 5.1)如果构造ModelAndView
		// 则框架会用渲染后的内容填充response,此时用户不可以设置view和view都必须为合法值
		// 具体可看-构造函数
		return new ModelAndView(ViewType.VELOCITY, model, view);
		//
		// 5.2--- return null表示不需要渲染
		// 此时用户自己处理header,以及response的content
		// 框架会直接把response发出去
		// return null;

	}

}
